package ftpClitentPool.core;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.springframework.stereotype.Component;

/**
 * @program: SpringBootDemos
 * @description:
 * @author: Kangsen
 * @create: 2021-09-24 11:26
 **/
@Slf4j
@Component
public class FtpClientPool {
    /**
     * ftp客户端连接池
     */
    private GenericObjectPool<FTPClient> pool;

    public FtpClientPool(FtpClientFactory ftpClientFactory){
        pool =new GenericObjectPool<FTPClient>(ftpClientFactory,ftpClientFactory.getFtpPoolConfig());
    }

    public FTPClient borrowObject() throws Exception{
        int i = 0;
        FTPClient client = null;
        while (true) {
            client = pool.borrowObject();
            try {
                if (client.sendNoOp()) {
                    return client;
                    //client.logout();//client.disconnect();//报错了也没意思了
                }
            } catch (Exception e) {
                pool.invalidateObject(client);
                log.warn("ftp连接池失败 ,第{}次", i++, e);
            }
        }
    }

    /**
     * 还   归还一个连接对象
     * @param ftpClient
     */
    public void returnObject(FTPClient ftpClient) {
        if (ftpClient != null) {
            pool.returnObject(ftpClient);
        }
    }
}
